import {
  Box,
  Button,
  Center,
  Flex,
  Image,
  Text,
  Menu,
  MenuButton,
  MenuList,
  MenuOptionGroup,
  MenuItemOption,
} from "@chakra-ui/react";
import { ChevronDownIcon, PlusSquareIcon } from "@chakra-ui/icons";
import {
  useContext,
  useEffect,
  useState,
  useRef,
  useCallback,
  useMemo,
} from "react";
import { MainContext } from "@/src/providers/MainProvider";
import { useTranslation } from "@/src/i18n";
import { useRouter } from "next/navigation";
import { WebHid } from "@/src/devices/WebHid";
import { usbDetect } from "@/src/shims/usb-detection";
import { motion } from "framer-motion";
import StarryCanvas from "@/src/components/Common/StarryCanvas";
import { getImgPath } from "@/src/utils";
import { MOUSE_MODELS } from "@/src/config/mouseModels";

const imgPath = getImgPath();

export default function HomePage() {
  const { deviceStatus, mouseStatus } = useContext(MainContext);
  const { t, lang, changeLanguage } = useTranslation("");
  const router = useRouter();
  const closeTimeoutRef = useRef(null);

  const [deviceList, setDeviceList] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0); // 用于强制刷新的状态

  // 用于防抖的定时器引用
  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 记录USB监听是否已启动
  const monitoringRef = useRef(false);

  const isElectron = useMemo(() => {
    if (typeof navigator !== "undefined") {
      return navigator.userAgent.toLowerCase().indexOf("electron") !== -1;
    } else {
      console.log("运行在服务器端，没有 navigator");
    }
  }, []);

  // 防抖刷新函数
  const debouncedRefresh = useCallback(() => {
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      setRefreshKey((prev) => prev + 1);
      debounceTimerRef.current = null;
    }, 300); // 300ms防抖时间
  }, []);

  // 当设备状态变化时更新列表
  useEffect(() => {
    debouncedRefresh();
  }, [deviceStatus, mouseStatus, debouncedRefresh]);

  // 使用refreshKey作为依赖项，当授权成功后强制刷新设备列表
  useEffect(() => {
    getDevices();
  }, [refreshKey]);

  // 添加USB设备插拔事件监听
  useEffect(() => {
    // 防止重复初始化监听
    if (monitoringRef.current) {
      return;
    }

    monitoringRef.current = true;

    // 处理USB设备连接事件
    const handleUSBConnect = () => {
      debouncedRefresh(); // 使用防抖函数
    };

    // 处理USB设备断开事件
    const handleUSBRemove = () => {
      debouncedRefresh(); // 使用防抖函数
    };

    // 监听HID设备连接/断开事件
    navigator.hid.addEventListener("connect", handleUSBConnect);
    navigator.hid.addEventListener("disconnect", handleUSBRemove);

    // 同时监听通用USB设备事件
    usbDetect.startMonitoring();
    usbDetect.on("connect", handleUSBConnect);
    usbDetect.on("remove", handleUSBRemove);

    // 组件卸载时清理监听器和防抖定时器
    return () => {
      monitoringRef.current = false;

      navigator.hid.removeEventListener("connect", handleUSBConnect);
      navigator.hid.removeEventListener("disconnect", handleUSBRemove);
      usbDetect.off("connect", handleUSBConnect);
      usbDetect.off("remove", handleUSBRemove);
      usbDetect.stopMonitoring();

      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
        debounceTimerRef.current = null;
      }
    };
  }, [debouncedRefresh]);

  const toDetail = (productName: string) => {
    if (!productName) return;

    const encoded = encodeURIComponent(productName);
    const isFile =
      typeof window !== "undefined" && window.location.protocol === "file:";

    if (isFile) {
      const url = new URL("detail/index.html", window.location.href);

      url.searchParams.set("productName", encoded);
      window.location.href = url.href; // file:///.../web/detail/index.html?productName=SM809
    } else {
      router.push(`/detail/?productName=${encoded}`); // 或 /detail?productName=...
    }
  };

  const getDevices = async () => {
    try {
      setIsLoading(true);

      let devices = await WebHid.devices(false, [
        { usagePage: 0xff01, usage: 0x0010 },
      ]);

      devices = devices.filter((device) => {
        return MOUSE_MODELS.some((model) =>
          device.productName.includes(model.id)
        );
      });

      if (devices && Array.isArray(devices)) {
        // 确保UI更新，即使设备列表内容相同
        setDeviceList([...devices]);
      } else {
        setDeviceList([]);
      }
      console.log("deviceList", devices);
    } catch (error) {
      setDeviceList([]);
    } finally {
      setIsLoading(false);
    }
  };

  const addDevice = async () => {
    try {
      setIsLoading(true);

      const devices = await navigator.hid.requestDevice({
        filters: [{ usagePage: 0xff01, usage: 0x0010 }],
      });

      if (devices && devices.length > 0) {
        // 授权成功后强制刷新设备列表，不使用防抖
        setRefreshKey((prevKey) => prevKey + 1);
      }
    } catch (error) {
      console.error("设备授权失败:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const getMouseImg = (productName: string) => {
    return `${imgPath}/products/mouse-v1000.png`;
  };

  return (
    <Box
      // className="main-bg"
      // bg="#211a31"
      minH="100vh"
      display="flex"
      flexDirection="column"
    >
      <StarryCanvas />

      <header className="flex justify-between items-center px-8 py-5 relative z-1">
        <Image src="logo.png" width="110px" alt="logo" />

        <Menu isLazy>
          {({ isOpen, onClose }) => {
            const handleMouseLeave = () => {
              closeTimeoutRef.current = setTimeout(() => {
                onClose();
              }, 300); // 300ms延迟关闭
            };

            const handleMouseEnter = () => {
              if (closeTimeoutRef.current) {
                clearTimeout(closeTimeoutRef.current);
              }
            };

            return (
              <Box>
                <MenuButton
                  as={Button}
                  rightIcon={<ChevronDownIcon />}
                  w="120px"
                  // onMouseEnter={(e) => e.currentTarget.click()}
                  // onMouseLeave={handleMouseLeave}
                >
                  <span suppressHydrationWarning>
                    {lang === "zh_CN" ? "简体中文" : "English"}
                  </span>
                </MenuButton>
                <MenuList
                  minW="120px"
                  maxW="120px"
                  w="120px"
                  // onMouseEnter={handleMouseEnter}
                  // onMouseLeave={handleMouseLeave}
                >
                  <MenuOptionGroup defaultValue={lang} type="radio">
                    <MenuItemOption
                      value="zh_CN"
                      onClick={() => {
                        changeLanguage("zh_CN");
                        onClose();
                      }}
                    >
                      简体中文
                    </MenuItemOption>
                    <MenuItemOption
                      value="en_US"
                      onClick={() => {
                        changeLanguage("en_US");
                        onClose();
                      }}
                    >
                      English
                    </MenuItemOption>
                  </MenuOptionGroup>
                </MenuList>
              </Box>
            );
          }}
        </Menu>
      </header>

      {/* 主要内容区域 */}
      <Center flex="1" className="relative z-1">
        <Flex direction="column" alignItems="center" gap={4}>
          {/* 添加新设备按钮 */}
          {!isElectron && (
            <Box>
              <Button
                leftIcon={<PlusSquareIcon />}
                className="primary-btn !font-family-msyh !rounded-[8px] mb-4"
                onClick={addDevice}
                isLoading={isLoading}
                loadingText={t("operationing")}
              >
                {t("addDevice")}
              </Button>

              {/* 设备列表状态 */}
              <Text fontSize="sm" color="white" className="text-center">
                {isLoading
                  ? t("loading")
                  : t("findDevice", { count: deviceList.length })}
              </Text>
            </Box>
          )}

          {/* 设备卡片 */}
          <Flex
            align="center"
            flexWrap="wrap"
            minHeight="500px"
            justifyContent="center"
          >
            {deviceList.map((item, index) => (
              <Box
                className="product-card"
                key={item.address || index}
                p={6}
                borderRadius="lg"
                boxShadow="sm"
                width="240px"
                overflow="hidden"
                cursor="pointer"
                onClick={() => toDetail(item.productName)}
                m={4}
                whileHover={{ y: -5 }}
                as={motion.div}
              >
                <Flex direction="column" alignItems="center" gap={4}>
                  <Text className="w-full truncate text-center" fontSize="20px">
                    {item.productName || "未知设备"}
                  </Text>

                  {/* 设备图片 */}
                  <Image
                    src={getMouseImg(item.productName)}
                    alt="设备图片"
                    width="160px"
                  />
                </Flex>
              </Box>
            ))}
          </Flex>

          {/* 底部提示文本 */}
          {!isElectron && (
            <Flex gap={1} color="white" fontSize="sm">
              <Text>{t("13_tip")}</Text>
            </Flex>
          )}
        </Flex>
      </Center>
    </Box>
  );
}
